
//Copyright 1997-2009 Syrinx Development, Inc.
//This file is part of the Syrinx Web Application Framework (SWAF).
// == BEGIN LICENSE ==
//
// Licensed under the terms of any of the following licenses at your
// choice:
//
//  - GNU General Public License Version 3 or later (the "GPL")
//    http://www.gnu.org/licenses/gpl.html
//
//  - GNU Lesser General Public License Version 3 or later (the "LGPL")
//    http://www.gnu.org/licenses/lgpl.html
//
//  - Mozilla Public License Version 1.1 or later (the "MPL")
//    http://www.mozilla.org/MPL/MPL-1.1.html
//
// == END LICENSE ==
using System;
using System.Collections.Generic;
using System.Text;

using Swaf;
using Swaf.BizObj;
using Swaf.Container;
using Swaf.Gui;
using Swaf.Security;


namespace eCom.Gui
{
	public class eComSalesOrderItemBizProc : BaseBusinessProcess
	{
		protected bool m_createdNewOrderId = false;
		public eComSalesOrderItemBizProc(ActiveBizProc procState) : base(procState) { }

		protected override void setupRuleNames()
		{
			m_getBizObjListRule = "getSalesOrderItems";
			m_updateBizObjRule = "updateSalesOrderItem";
			m_deleteBizObjRule = "deleteSalesOrderItem";
			//State.State.put("EditModeSessionKey", true);
			m_getMasterBizObjListRule = "getProducts";
		}

		protected override object[] getMasterBizObjListBizRuleParams(object mlpid)
		{
			FlexiMap m = new FlexiMap();
			m.put("parentId", m_procState.get("mlpid"));
			DetailLevel listLevel = (State.State.get("listDetailLevel") is DetailLevel) ? (DetailLevel)State.State.get("listDetailLevel") : DetailLevel.fullDetails;
			m.put("listDetailLevel", listLevel);
			NameAddressStack s = new NameAddressStack(State.State, m);
			return new object[] { s, m_filterSortCriteria };
		}
		public override IBizObj CurrentBizObj
		{
			get
			{
				IBizObj cur = base.CurrentBizObj;
				if (cur == null)
				{
					cur = createNewBizObj();
					State.InProgressAddBizObj = cur;
				}
				return cur;
			}
		}

		protected override object[] getBizObjListRuleParameters(object parentId, IBizObj filterSort)
		{
			return new object[] { parentId};
		}

		protected override bool shouldCallGetBizObjListRule(object parentBizObjId)
		{
			return true;
		}


		public override IResults updateBizObj(IBizObj obj)
		{
			if (!obj.isDirty() || (obj.isNew && (int)obj.get("quantity") == 0))
				return null;
			IResults rc = base.updateBizObj(obj);
			forceParentBizProcUpdates();
			return rc;
		}

		public void addOneToCart(object itemId)
		{
			bool forceChildren = false;
			IBizObj product = null;
			Swaf.BGuid.Guid orderItemId = itemId as Swaf.BGuid.Guid;
			if (orderItemId == null && !Swaf.BGuid.Guid.TryParse(itemId.ToString(), out orderItemId))
			{
				App.Log.println(Swaf.Logging.LoggingLevels.High, "addOneToCart: {0}", itemId);
				product = m_currentBizObj = SourceBizObjs.search("uniqueId", itemId.ToString(), false);
				m_retrievedCurrentBizObj = true;
				forceChildren = true;
			}
			else
				product = selectBizObj(orderItemId, null);

			if (product != null)
			{
				if (product.get("orderId") == null)
					product.put("orderId", App.ruleMgr.execute("getCurrentSalesOrderId").CallResults);
				product.put("quantity", (int)product.get("quantity") + 1);
				updateBizObj();
				if (Cmn.IsTrue(ActiveCompany.get("settings.checkoutOnAddToCart")))
				{
					ActiveBizProc checkout = m_procState.getParentBizProc("checkout");
					if (checkout != null)
					{
						IAction moveNext = checkout.BizProc.Actions["MoveNext"];
						if (moveNext != null)
							moveNext.trigger();
					}
				}
			}
			else
			{
				App.Log.println(Swaf.Logging.LoggingLevels.High, "addOneToCart: could not find itemid:{0}", itemId);
			}

            if (forceChildren)
                clearDependentChildBizProcs();
				//forceChildBizProcUpdates();

			//Swaf.BGuid.Guid orderItemId = new Swaf.BGuid.Guid(itemId.ToString());
			if (orderItemId != null)
			{
			    //App.ruleMgr.execute("addOneQuantityOfProductToCurrentSalesOrder", orderItemId);
			    forceParentBizProcUpdates();
			}
		}

		public override void updateActionState()
		{
			base.updateActionState();
			((GenericAction)Actions["AddBizObj"]).Availability = CanEdit ? ActionAvailability.enabled : ActionAvailability.none;
			((GenericAction)Actions["NotAuthAddOne"]).Availability = Cmn.IsFalse(CurrentUser.get("authenticated")) ? ActionAvailability.enabled : ActionAvailability.none;
		}
		protected override void prepareForMasterList(ref IBizObjList masterList, ref IBizObjList baseList)
		{
			if(baseList != null)
				foreach (IBizObj obj in baseList)
				{
					IBizObj prod = null;
					if(obj.get("product.id") != null)
						prod = masterList.search("id", obj.get("product.id"));
					//System.Diagnostics.Debug.Assert(prod != null);
					if(prod != null)
						obj.put("product", prod);
				}
		}
		protected override object[] getUpdateBizRuleParameters(IBizObj bizObj)
		{
			if (bizObj.isNew)
				bizObj.put("id", new Swaf.BGuid.Guid());
			return new object[] { bizObj };
		}

		public override IBizObj createNewBizObj()
		{
			IBizObj soItm = App.bizObjMgr.create("eComSalesOrderItem");
			soItm.put("id",new Swaf.BGuid.Guid());
			soItm.put("orderId", m_procState.get("pid"));
			return soItm;
		}
		
		public override Privileges CurrentEditPrivilege
		{
			//TODO: this is true only if this is that user's order, other wise it should be based on the "manage sales orders" privege 
			get { return Privileges.Delete; }
		}

		protected override void setupActions()
		{
			base.setupActions();
			Actions.addAction(new GenericAction("AddOne", true, true, this, addOneToCart));
			Actions.addAction(new GenericAction("NotAuthAddOne", true, true, this, addOneToCart));
		}

		//
		protected override bool validateBizObj(IBizObj obj)
		{
			IResults rc = App.ruleMgr.execute("validateOrderItem", obj);
			List<UserMessage> msgs = rc.CallResults as List<UserMessage>;
			if (msgs == null)
				return true;
			m_procState.BPC.Messenger.addRange(msgs);
			return false;
		}

	}
}
